package com.bianmaba.services.datacollection;

import com.bianmaba.beans.datacollection.CollectionSchedule;
import com.bianmaba.beans.datacollection.CollectionTask;
import com.bianmaba.beans.datacollection.TaskInstance;
import com.bianmaba.dc.bean.JobParameter;
import com.bianmaba.dc.bean.TaskStatus;
import com.bianmaba.dc.bean.TaskType;
import com.bianmaba.jobs.collection.monitor.CollectorStatusMonitor;
import com.bianmaba.repositories.datacollection.TaskInstanceRepository;
import com.bianmaba.services.datacollection.quartiz.QuartzTaskManager;
import com.bianmaba.spring.web.service.BaseService;
import org.quartz.JobDataMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;


/**
 * @see ICollectionTaskService
 */
@Service
public class TaskInstanceService extends BaseService<TaskInstance, String> implements ITaskInstanceService {
    private static final Logger LOG = LoggerFactory.getLogger(TaskInstanceService.class);
    @Autowired
    private QuartzTaskManager quartzTaskManager;
    @Autowired
    private TaskInstanceRepository repository;

    @Override
    public TaskInstanceRepository getRepository() {
        return repository;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public TaskInstance updateStatus(String taskInstanceId, Integer status) {
        TaskInstance taskInstance = getById(taskInstanceId);
        taskInstance.setStatus(status);
        if (status.intValue() > 2) {
            taskInstance.setEndTime(Calendar.getInstance().getTime());
        }
        this.save(taskInstance);
        return taskInstance;
    }

    @Override
    public Integer getStatus(String taskInstanceId) {
        TaskInstance taskInstance = getById(taskInstanceId);
        return taskInstance.getStatus();
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    public TaskInstance createTaskInstance(CollectionSchedule schedule, CollectionTask task, String executor) {
        TaskInstance instance = new TaskInstance(task.getName(), task.getProjectId(), new Date(), null, TaskStatus.WAIT.getIndex(), executor, task, schedule);
        return save(instance);
    }

    @Override
    public void startStatusCheck(String id) {
        JobDataMap dataMap = new JobDataMap();
        dataMap.put(JobParameter.TASK_INSTANCE_ID.getName(), id);
        dataMap.put(JobParameter.TASK_TYPE.getName(), TaskType.DATA_COLLECTION_TASK_STATUS_CHECK);
        String jobName = id;
        String groupName = "采集任务状态监听";
        quartzTaskManager.executeOnceJob(CollectorStatusMonitor.class, jobName, groupName, dataMap);
    }
}
